// 头像缓存工具
class AvatarCache {
  constructor() {
    this.memoryCache = new Map()
    this.loadingCache = new Set()
    this.storageKey = 'avatar_cache'
    this.maxCacheSize = 50 // 最大缓存数量
    this.cacheTimeout = 24 * 60 * 60 * 1000 // 24小时过期
    
    // 启动时清理过期缓存
    this.cleanExpiredCache()
  }

  // 获取缓存键名
  getCacheKey(url) {
    return url ? btoa(url).replace(/[^a-zA-Z0-9]/g, '') : ''
  }

  // 从localStorage获取缓存
  getFromStorage(key) {
    try {
      const data = localStorage.getItem(`${this.storageKey}_${key}`)
      if (data) {
        const parsed = JSON.parse(data)
        // 检查是否过期
        if (Date.now() - parsed.timestamp < this.cacheTimeout) {
          return parsed.data
        } else {
          // 过期则删除
          localStorage.removeItem(`${this.storageKey}_${key}`)
        }
      }
    } catch (error) {
      console.warn('读取头像缓存失败:', error)
    }
    return null
  }

  // 保存到localStorage
  saveToStorage(key, data) {
    try {
      const cacheData = {
        data: data,
        timestamp: Date.now()
      }
      localStorage.setItem(`${this.storageKey}_${key}`, JSON.stringify(cacheData))
    } catch (error) {
      console.warn('保存头像缓存失败:', error)
      // 如果存储失败（可能是空间不足），清理一些缓存
      this.clearOldCache()
    }
  }

  // 获取缓存的头像URL
  getCachedAvatar(originalUrl) {
    if (!originalUrl || !originalUrl.startsWith('http')) {
      return originalUrl
    }

    const cacheKey = this.getCacheKey(originalUrl)
    
    // 优先从内存缓存获取
    if (this.memoryCache.has(cacheKey)) {
      return this.memoryCache.get(cacheKey)
    }

    // 从localStorage获取
    const cachedData = this.getFromStorage(cacheKey)
    if (cachedData) {
      // 同时缓存到内存
      this.memoryCache.set(cacheKey, cachedData)
      return cachedData
    }

    // 如果没有缓存且未在加载中，开始预加载
    if (!this.loadingCache.has(originalUrl)) {
      this.preloadImage(originalUrl)
    }

    return originalUrl
  }

  // 预加载图片并缓存
  async preloadImage(url) {
    if (!url || this.loadingCache.has(url)) {
      return
    }

    this.loadingCache.add(url)
    const cacheKey = this.getCacheKey(url)

    try {
      // 创建图片对象进行预加载
      const img = new Image()
      img.crossOrigin = 'anonymous'
      
      await new Promise((resolve, reject) => {
        const timeout = setTimeout(() => {
          reject(new Error('头像加载超时'))
        }, 15000) // 15秒超时

        img.onload = () => {
          clearTimeout(timeout)
          try {
            // 创建canvas转换为base64
            const canvas = document.createElement('canvas')
            const ctx = canvas.getContext('2d')
            
            // 限制图片尺寸以节省存储空间
            const maxSize = 200
            let { width, height } = img
            
            if (width > maxSize || height > maxSize) {
              const ratio = Math.min(maxSize / width, maxSize / height)
              width *= ratio
              height *= ratio
            }
            
            canvas.width = width
            canvas.height = height
            ctx.drawImage(img, 0, 0, width, height)
            
            const dataURL = canvas.toDataURL('image/jpeg', 0.8)
            
            // 缓存到内存和localStorage
            this.memoryCache.set(cacheKey, dataURL)
            this.saveToStorage(cacheKey, dataURL)
            
            console.log(`✅ 头像已缓存: ${url.substring(0, 50)}...`)
            resolve(dataURL)
          } catch (error) {
            console.warn('头像转换失败，使用原URL:', error)
            this.memoryCache.set(cacheKey, url)
            resolve(url)
          }
        }
        
        img.onerror = () => {
          clearTimeout(timeout)
          console.warn(`❌ 头像加载失败: ${url}`)
          // 缓存原URL避免重复尝试
          this.memoryCache.set(cacheKey, url)
          resolve(url)
        }
        
        img.src = url
      })
    } catch (error) {
      console.warn('预加载头像失败:', error)
      this.memoryCache.set(cacheKey, url)
    } finally {
      this.loadingCache.delete(url)
    }
  }

  // 清理过期缓存
  cleanExpiredCache() {
    try {
      const keysToRemove = []
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i)
        if (key && key.startsWith(this.storageKey)) {
          const data = localStorage.getItem(key)
          if (data) {
            const parsed = JSON.parse(data)
            if (Date.now() - parsed.timestamp >= this.cacheTimeout) {
              keysToRemove.push(key)
            }
          }
        }
      }
      keysToRemove.forEach(key => localStorage.removeItem(key))
      if (keysToRemove.length > 0) {
        console.log(`🧹 清理了 ${keysToRemove.length} 个过期头像缓存`)
      }
    } catch (error) {
      console.warn('清理过期缓存失败:', error)
    }
  }

  // 清理旧缓存（当存储空间不足时）
  clearOldCache() {
    try {
      const cacheItems = []
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i)
        if (key && key.startsWith(this.storageKey)) {
          const data = localStorage.getItem(key)
          if (data) {
            const parsed = JSON.parse(data)
            cacheItems.push({ key, timestamp: parsed.timestamp })
          }
        }
      }
      
      // 按时间排序，删除最旧的一半
      cacheItems.sort((a, b) => a.timestamp - b.timestamp)
      const itemsToRemove = cacheItems.slice(0, Math.floor(cacheItems.length / 2))
      itemsToRemove.forEach(item => localStorage.removeItem(item.key))
      
      console.log(`🧹 清理了 ${itemsToRemove.length} 个旧头像缓存`)
    } catch (error) {
      console.warn('清理旧缓存失败:', error)
    }
  }

  // 强制更新头像缓存
  updateAvatar(url) {
    if (!url) return
    
    const cacheKey = this.getCacheKey(url)
    
    // 清除现有缓存
    this.memoryCache.delete(cacheKey)
    localStorage.removeItem(`${this.storageKey}_${cacheKey}`)
    
    // 重新加载
    this.preloadImage(url)
  }

  // 清除所有缓存
  clearCache() {
    this.memoryCache.clear()
    this.loadingCache.clear()
    
    // 清除localStorage中的头像缓存
    try {
      const keysToRemove = []
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i)
        if (key && key.startsWith(this.storageKey)) {
          keysToRemove.push(key)
        }
      }
      keysToRemove.forEach(key => localStorage.removeItem(key))
      console.log('🧹 已清除所有头像缓存')
    } catch (error) {
      console.warn('清除缓存失败:', error)
    }
  }

  // 获取缓存统计信息
  getCacheStats() {
    const memorySize = this.memoryCache.size
    let storageSize = 0
    try {
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i)
        if (key && key.startsWith(this.storageKey)) {
          storageSize++
        }
      }
    } catch (error) {
      console.warn('获取缓存统计失败:', error)
    }
    
    return {
      memory: memorySize,
      storage: storageSize,
      loading: this.loadingCache.size
    }
  }
}

// 创建全局实例
const avatarCache = new AvatarCache()

export default avatarCache 